package i2.application.checklist.services.impl;

import i2.application.checklist.dao.QuestionDao;
import i2.application.checklist.entities.Question;
import i2.application.checklist.services.QuestionService;
import i2.application.fmw.aspects.Validation;
import i2.application.fmw.exceptions.ValidationException;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class QuestionServiceImpl implements QuestionService {

	private static final Logger logger = LoggerFactory.getLogger(QuestionServiceImpl.class);

	private QuestionDao questionDao;
	
	@Override
	public List<Question> getAllQuestions() {
		return questionDao.findAll();
	}
	
	@Validation
	@Override
	public void createQuestion(Question question) {
		this.questionDao.add(question);
	}
	
	@Validation
	@Override
	public void updateQuestion(Question question) {
		this.questionDao.update(question);
	}

	@Override
	public void deleteQuestion(Question question) {
		// il est interdit de supprimer une question qui a des reponses
		if (questionDao.hasReponses(question)) {
			logger.warn("Action impossible : la question d'id {} a des reponses", question.getId());
			throw new ValidationException("question.nom", "question.has.reponses");
		}

		this.questionDao.delete(question);
	}

	@Override
	public Question getQuestion(Question question) {
		return questionDao.findById(question.getId());
	}

	@Override
	public void setQuestionDao(QuestionDao questionDao) {
		this.questionDao = questionDao;
	}
	
}
